<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet"
      href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
    <style>
      #pic-box{
         height: 500px;
      }
      #pic{
         width: auto;
         height: auto;
         max-width: 100%;
         max-height: 100%;
      }
    </style>
  </head>
  <body>

    <div class="d-flex justify-content-center mt-3">
      <button id="btn" type="button" class="btn btn-outline-primary mr-3">Get-A-Cute-Dog-Img</button>
      <button id="btn1" type="button" class="btn btn-outline-primary">Get-A-Cute-Cat-Img</button>
    </div>
    <img id="pic" src="" alt="">
    <div id="state" class="d-flex justify-content-center mt-3">State: none</div>
    <div class="d-flex justify-content-center mt-3">
      <button id="downloadBtn" class="btn btn-outline-danger">Download</button>
    </div>
  </body>
  <script>
    const dogBtn = document.getElementById('btn');
    const catBtn = document.getElementById('btn1');
    const xhrPromise = (url) => {
      return new Promise((resolve,reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET',url);
        xhr.send();
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4){
                if(xhr.status >= 200 && xhr.status <300) {
                  resolve(xhr.response);
            }else{
              reject('failed', xhr.status);
            }
          }
        };
      })};
      
    let statu = document.getElementById('state');
    let pic = document.getElementById('pic');

    function update(message){
       statu.innerHTML = 'request-successed-loading-image...';
       pic.src = message;
       pic.onload = function(){
         statu.innerHTML = 'over';
       }
    }

    catBtn.addEventListener('click',async () => {
      statu.innerHTML = 'waiting...';
      try {
        let data = await xhrPromise('http://127.0.0.1:3000/api/cat-image');
        let message = JSON.parse(data)[0].url;
        update(message);
      } catch (e) {
        statu.innerHTML = e;
      } 
    })

    dogBtn.addEventListener('click',async () => {
      statu.innerHTML = 'waiting...';
      try {
        let data = await xhrPromise('http://127.0.0.1:3000/api/dog-image');
        let {message} = JSON.parse(data);
        update(message);
      } catch (e) {
        statu.innerHTML = e;
      } 
    })

  </script>
</html>